#ifndef __PWLIB_LIBFILE_HPP__
#define __PWLIB_LIBFILE_HPP__

namespace purewell
{

typedef struct __pw_shinst_t
{
	void*		p;
	int			fd;
	size_t		size;

	__pw_shinst_t() : p(NULL), fd(-1), size(0) {}
} __pw_shinst_t;

bool __PWCreateSharedInstance(__pw_shinst_t& out, size_t size);

void __PWDestroySharedInstance(__pw_shinst_t& in);

int __PWCreateUnnamedSharedMemoryTemp(void);

struct timespec& __PWDiffTimespec(struct timespec& res,
	const struct timespec& ts1, const struct timespec& ts2);

#if !defined(__PW_HAVE_GETTIMEOFDAY) && defined(__PW_HAVE_GETSYSTEMTIMEASFILETIME)
int gettimeofday(struct timeval* tv, void*);
#endif//!__PW_HAVE_GETTIMEOFDAY && __PW_HAVE_GETSYSTEMTIMEASFILETIME

uint64_t __PWToMSecond(const struct timeval& tv);

uint64_t __PWGetNow(void);

#ifdef WIN32
int __PWGetFDFromHandle(const HANDLE hdl, int flags);
HANDLE __PWGetHandleFromFD(int fd);
#endif//WIN32

inline
bool
__PWSetBoolean(int& output, int input, bool v)
{
	if (v)
	{
		output |= input;
	}
	else
	{
		output &= ~input;
	}

	return v;
}

inline
bool
__PWGetBoolean(int flags1, int flags2)
{
	return (flags1 & flags2) != 0;
}

inline
bool
__PWGetFlags(bool& chk, int fd, int flags)
{
#if defined(__PW_HAVE_FCNTL)
	int _flags( fcntl(fd, F_GETFL) );
	if ( -1 == _flags ) return false;

	chk = 0 != ( _flags & flags );
	return true;
#else
	return false;
#endif
}

inline
bool
__PWSetFlags(bool set, int fd, int flags)
{
#if defined(__PW_HAVE_FCNTL)
	int _flags( fcntl(fd, F_GETFL) );
	if ( -1 == _flags ) return false;

	if ( set )
	{
		_flags |= flags;
	}
	else
	{
		_flags &= ~flags;
	}

	return ( -1 != fcntl(fd, F_SETFL, _flags) );
#else
	return false;
#endif
}

inline
bool
__PWGetFDFlags(bool& chk, int fd, int flags)
{
#if defined(__PW_HAVE_FCNTL)
	int _flags( fcntl(fd, F_GETFD) );
	if ( -1 == _flags ) return false;

	chk = 0 != ( _flags & flags );
	return true;
#else
	return false;
#endif
}

inline
bool
__PWSetFDFlags(bool set, int fd, int flags)
{
#if defined(__PW_HAVE_FCNTL)
	int _flags( fcntl(fd, F_GETFD) );
	if ( -1 == _flags ) return false;

	if ( set )
	{
		_flags |= flags;
	}
	else
	{
		_flags &= ~flags;
	}

	return ( -1 != fcntl(fd, F_SETFD, _flags) );
#else
	return false;
#endif
}

};//namespace purewell

#endif//!__PWLIB_LIBFILE_HPP__

